package job

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/util/gconv"
	"snake/app/service/script"
	"snake/library/base"
	"snake/app/model/ops"
	ops_svc "snake/app/service/ops"
	"k8s.io/apimachinery/pkg/util/uuid"
)

type Action struct {
	base.BaseRouter
}

// path: /run
func(action *Action) Run(r *ghttp.Request) {
	//glog.Info(r)
	//id := r.GetInt64("id")
    //声明一个任务
	glog.Info("receive run script request....")
    job := ops.Job{}
    rmap := r.GetMap()
	job.ScriptId = gconv.Int(rmap["id"].(string))
    job.JobId = gconv.String(uuid.NewUUID())
    job.Tasks = make([]ops.Task,0)
	job.Status = "created"
    //执行的主机列表
	hostList := rmap["hostList"].(map[string]interface{})
	for k,v := range hostList {
		//声明一个子任务task
		task := ops.Task{}
		task.Id = gconv.Int(k)
		task.ScriptId = job.ScriptId
		task.Host = v.(map[string]interface{})
		task.Status = "created"
		task.Log = ""
		job.Tasks = append(job.Tasks, task)
	}
	respData := make(map[string]string, 0)
	respData["jobId"] = job.JobId
	//创建任务后返回任务ID, 再往下执行任务
	glog.Info("create run script task:", job)
	go script.RunJob(&job)
	base.Succ(r, respData)
}

// path: /job/get/{id}
func (action *Action) Get(r *ghttp.Request) {
	id := r.GetString("id")
	model, err := ops_svc.GetByJobId(id)
	if err != nil {
		base.Fail(r, err.Error())
	}
	base.Succ(r, model)
}

// path: /page
func (action *Action) Page(r *ghttp.Request) {
	form := base.NewForm(r.GetMap())
	page, err := ops_svc.Page(&form)
	if err != nil {
		glog.Error("page error", err)
		base.Error(r, err.Error())
	}
	base.Succ(r,
		g.Map{
			"page":    form.Page,
			"rows":    page,
			"total":   form.TotalPage,
			"records": form.TotalSize,
		})
}